<?php

/**
 * @author liyi
 * @copyright 2018.12.10
 */
namespace Paolgame\Controller;
use Common\Controller\ApiController;
use Think\Model;
use Think\Log;

// 泡泡龙游戏
class IndexController extends ApiController {

    const GAME_TYPE = 'Paolgame';  // 游戏类型

    const QID_UID ='paol:user:%s:type:%s:qid:%s'; // 用户分享到群限制

    const PAOL_SHARE = "paols:share";  // 分享次数

    const CACHE_KEY = 'paol';  // 游戏全局缓存键 - redis

    const DB_USER_NAME = 'paol_game.users'; // 游戏用户数据表

    const DB_INVITELOG_NAME = 'paol_game.invite_log'; // 游戏邀请数据表

    const INVITE = "paol:invite:sid:%"; // 邀请次数

    const PAOL_KEY = "paol:%s:sid:%s"; // 渠道来源缓存键

    const PAOL_COUNT_KEY = "paol:count"; // 渠道来源统计缓存键

    const PAOL_RANK_LIST = "paol:rankList"; // 排行榜列表(缓存键)

    const PAOL_RANK_LIST2 = "paol:rankList2"; // 排行榜列表(缓存键)

    const PAOL_DBID = 3; // 缓存数据编号

    public function __construct()
    {
        parent::__construct();

        $uid = $this->isLogin(self::GAME_TYPE);
        $id = I('id','','int');

        if(empty($uid)) {
            $uid = $id;
            //$uid = $this->isParamLogin($id);
        }
        if (!$uid) {
            $this->response(1,'请先登录');
        }
        $source = I('source',0,'int');  // 渠道来源
        $this->sid = $source;   // 渠道
        $this->uid = $uid;      // 用户登录id
    }

    // 排行榜
    public function rankingList()
    {
        $uid = isset($this->uid)?$this->uid:I('post.id');
        $gold = I('gold','','string');
        $checkpoint= I('checkpoint','','string');   //关卡等级
        $type = I('type',1,'string');   // 1：关卡/无尽

        $redis = REDIS('activity');
        $redis->select(2);
        $hash_key = self::PAOL_RANK_LIST;//   Paol:rankList
        $hash_key2 = self::PAOL_RANK_LIST2;//   Paol:rankList2

        $map['nickname'] = array('neq','');
        $map['avatar'] = array('neq','');

        if($type==1){   // 关卡
            $ret = $this->getRankList($hash_key,true,2,'checkpoint');// 读取缓存排行榜
            // 初始化缓存
            if(empty($ret)) {
                $map['black_list'] = 1;
                $map['status'] = 2;
                $map['checkpoint'] = array('neq','');
                $ret = M('users')->field('id,nickname,avatar,gold,score,checkpoint')->where($map)->order('checkpoint desc')->limit(200)->select();
                $mysql = M('users')->getLastSql();
                log::write("ranklist:".$mysql,"SUCCESS");
                foreach($ret as $k=>$v) {
                    if(!empty($v['nickname']) && !empty($v['avatar'])){ // 必须授权
                        $id = $v['id'];
                        $flag = $redis->hSet($hash_key,$id, json_encode($v));
                    }
                }
            }
        }else{  // 无尽
            $ret = $this->getRankList($hash_key2,true,2,'endless_score');// 读取缓存排行榜

            // 初始化缓存
            if(empty($ret)) {
                $map['black_list'] = 1;
                $map['status'] = 2;
                $map['endless_score'] = array('neq','');
                $ret = M('users')->field('id,nickname,avatar,gold,score,endless_score,best_endless_score,medal')->where($map)->order('endless_score desc')->limit(200)->select();
                $mysql = M('users')->getLastSql();
                log::write("ranklist2:".$mysql,"SUCCESS");
                foreach($ret as $k=>$v) {
                    if(!empty($v['nickname']) && !empty($v['avatar'])){ // 必须授权
                        $id = $v['id'];
                        $flag2 = $redis->hSet($hash_key2,$id, json_encode($v));
                    }
                }
            }
        }


        if(!empty($uid) && !empty($checkpoint) && $type==1){
            $lastPoint = null;
            foreach ($ret as $key => $val) {
                if($val['id'] == $uid){
                    $lastPoint = intval($val['checkpoint']);
                    break;
                }
            }
            // 当总金币大于缓存记录 更新个人缓存记录
            if($checkpoint > $lastPoint) {
                $where['id'] = $uid;    // 用户id
                $userInfo = M('users')->field('id,nickname,avatar,gold,checkpoint')->where($where)->find();
                $data = array('id'=>$userInfo['id'],'gold'=>$gold,'checkpoint'=>$checkpoint,'nickname'=>$userInfo['nickname'],'avatar'=>$userInfo['avatar']);
                //点击排行版更新用户数据
                $this->setRankList($hash_key,2,$data,$userInfo['id'],'checkpoint',$checkpoint);//   更新缓存
                M('users')->where($where)->save(array('checkpoint'=>$checkpoint));  //更新数据库

                $ret = $this->getRankList($hash_key,true,2,'checkpoint');
            }
        }
        $this->response(0, "OK",array('randList'=>$ret));
    }


    // 积分排行榜
    public function gradeList()
    {
        $uid = I('id','','string');
        if ( !$uid ){
            $this->response(1,'请先登录');
        }

        $ret = array();
        $model = M('users');
        $field = "id,nickname,avatar,grade";
        $map['status'] = 2;
        $map['grade'] = array('neq',0);

        $ret = $model->field($field)->where($map)->order('grade desc')->limit(200)->select();
        $this->response(0,"ok",$ret);
    }


    // 招人接口 邀请记录
    public function inviteRecord()
    {
        $uid = isset($this->uid)?$this->uid:I('post.id');
        $sid = $this->sid;
        $invite_uid = I('invite_uid',0,'int'); //邀请人用户
        $type = I('type',1,'int'); // 邀请类型 1:每日邀请 2：招募保安 3：招募会计 4：招募经理 5：招募总监
        $time = date('Y-m-d');
        $dbname = self::DB_INVITELOG_NAME; // const DB_INVITELOG_NAME = 'paol_game.invite_log'; // 游戏邀请数据表
        $dbname2 = self::DB_USER_NAME;  //   const DB_USER_NAME = 'paol_game.users'; // 游戏用户数据表
        $cacheKey = self::CACHE_KEY; // const DB_USER_NAME = 'paol_game.users'; // 游戏用户数据表
        $cacheval =  sprintf(self::INVITE,$sid) ; // 缓存值 const INVITE = "paol:invite:sid:%"; // 邀请次数

        $dbId = self::PAOL_DBID;    // 邀请数据库
        if( $uid != $invite_uid ) {  //如果不是自己邀请自己
            // 转发邀请记录
            $typeForward = array("101", "102", "103");
            if (in_array($type, $typeForward)) {
                $type_table = 'paol';   // redis表
                $this->getForward($uid, $invite_uid, $type_table, $type);
            }
            $incr = $this->commInviteRecord_api($uid,$invite_uid,$type,$time,$dbname,$dbname2,$cacheKey,$cacheval,$dbId);
            $this->getChannelCount(self::PAOL_COUNT_KEY,$sid,'invite',$incr,$dbId);
        }else{
            $this->response(3, "自己不能邀请自己");
        }

    }


    // 招人接口 邀请列表
    public function hiringList() {
        $uid = $this->uid;
        //$uid = isset($this->uid)?$this->uid:I('post.id');
        // 邀请类型 1:每日邀请 2：招募保安  3：招募会计 4：招募经理 5：招募总监  6:金币加速
        $post = I('post.type');  // type[2,3,4,5,6]
        if(!empty($post)){
            if(is_array($post)){
                $type = $post;
            }else{
                $type = json_decode($post,true);
            }
        }else{
            $type=1;
        }

        $sort = I('post.sort'); //
        $dbname = self::DB_INVITELOG_NAME; // const DB_INVITELOG_NAME = 'paol_game.invite_log'; // 游戏邀请数据表
        $dbname2 = self::DB_USER_NAME;  //  const DB_USER_NAME = 'paol_game.users'; // 游戏用户数据表
        if($type !=99){
            if($sort ==1){
                $time = date('Y-m-d');// 今日邀请
            }else{
                $time = '';// 所有邀请
            }
        }

        $list = $this->commUserInvite_api($uid,$type,$dbname,$dbname2,$time);// 邀请记录
        $info =$temp =array();
        if(!empty($list['userInfo'])) {
            // 按请求类型输出所属信息
            foreach( $list['userInfo'] as $k => $v) {
                $info[$v['type']][] = $v;//所有标识
                unset($temp);
            }
        }

        //$info = array('2'=>$guard,'3'=>$finance,'4'=>$manager,'5'=>$director,'6'=>$speed,'number'=>$list['number']);
        $num = $list['number'];
        $this->response(0, "ok",$info,$num);

    }


    // 每日任务列表
    public function everyDayTask() {

        $uid = $this->uid;
        $time = date('Y-m-d');

        $dbname = self::DB_INVITELOG_NAME;
        $dbname2 = self::DB_USER_NAME;

        $list = $this->commUserInvite($uid,$type=1,$dbname,$dbname2,$time);

        $this->response(0, "ok",$list);
    }


    // 记录用户点击分享按钮的次数
    public function setShare() {
        $id = I('id','','string'); // 用户userid
        $type = I('type',1,'int');  // 1:分享次数 2：分享完成(暂停) 3：看完视频次数 4：点击视频次数
        $sid = $this->sid;  // 渠道来源

        if(!in_array($type,array(1,3,4))) {
            $this->response(1,'非法的分享类型');
        }
        $arr = array(1=>'share',3=>'video_close',4=>'video_click');
        $typeName = $arr[$type];

        $userKey = self::CACHE_KEY;
        $userVal = sprintf(self::PAOL_KEY,$typeName,$sid);  //用户主键分享到群
        $countKey = self::PAOL_COUNT_KEY;

        $incr = $this->countLog($userKey,$userVal);  // 记录看完视频的次数

        $this->getChannelCount($countKey,$sid,$typeName,$incr);

        $this->response(0,'ok');
    }


    // 匹配系统用户 按积分区间分配
    public function getMatchUser() {
        $uid = I('id',0,'int');
        $grade = I('grade',0,'int');
        $limit = 20;

        $start_grade = $grade < 1000 ? $grade : $grade - 1000;
        $end_grade =  $grade + 1000;

        $field = 'id,nickname,avatar,good_score,grade';

        $where['status'] = 2;
        $userList = M('users')->field($field)->where("grade > $start_grade AND grade <= $end_grade AND grade != 0 AND status = 2")->limit($limit)->select();

        $total = $limit - count($userList);
        $lastList = array();
        if($total > 0 ) {
            $where['grade'] = array('elt',$start_grade);
            $lastList = M('users')->field($field)->where($where)->order('grade desc')->limit($total)->select();
        }

        $info = !empty($lastList) ? array_merge($userList,$lastList) : $userList;

        // 过滤掉自己
        foreach($info as $k=>$v) {
            if($uid == $v['id'] ) {
                unset($info[$k]);
            }
        }

        shuffle($info);  // 打乱数组排序
        $this->response(0,'ok',$info);

    }


    // 设置金币
    public function setGolds() {
        $uid = isset($this->uid)?$this->uid:I('post.id');
        $gold = I('gold','0','string');
        $diamonds = I('diamonds','0','string');

        if(!empty($gold)) {
            $data['gold'] = $gold;
        }else{
            $this->response(1,"设置参数gold不能为空");
        }
        if(!empty($diamonds)) {
            $data['diamonds'] = $diamonds;
        }

        $map['id'] = $uid;
        $ret = M('users')->where($map)->save($data);
        if($ret){
            $this->response(0,"操作成功");
        }

    }


    // 游戏结束记录 2019年1月15日 14:31:56
    public function addGameResult() {

        $uid = I('id',0,'int');
        $score = I('score',0,'string');//用户成绩
        $gold = I('gold',0,'string');  //金币
        $diamonds = I('diamonds',-1,'string');  //金币
        $grade = I('grade',-1,'string');//积分
        $checkpoint = I('post.checkpoint',0,'intval');;//关卡成绩
        $type = I('type',1,'int');  // 1: 正常模式 2：积分模式
        $endless_score = I('endless_score',0,'string');//当前无尽分
        $medal = I('medal',0,'string');//勋章分数
        $best_endless_score = I('best_endless_score',0,'string');//最佳无尽分排名
        $map['id'] = $uid;
        $userInfo = M('users')->field('id,nickname,avatar,gold,score,checkpoint')->where($map)->find();

        if(empty($gold)) {
            $data['gold'] = $gold;
        }
        if($diamonds != '-1') {
            $data['diamonds'] = $diamonds;
        }
        if($score){
            if($score > $userInfo['score']) {
                $data['score'] = $score;// 最好成绩
            }
        }
        if($type == 1) {  // 正常模式
            if(empty($checkpoint)){
                $this->response('3','关卡成绩不能为空');
            }
            if($checkpoint > $userInfo['checkpoint']){
                $redis = REDIS('activity');
                $redis->select(2);
                $hash_key = self::PAOL_RANK_LIST;//   Paol:rankList
                $data = array('id'=>$userInfo['id'],'gold'=>$gold,'checkpoint'=>$checkpoint,'nickname'=>$userInfo['nickname'],'avatar'=>$userInfo['avatar']);
                //关卡排行榜
                $this->setRankList($hash_key,2,$data,$userInfo['id'],'checkpoint',$checkpoint);//   更新缓存
                $data['checkpoint'] = $checkpoint;// 关卡成绩
                $data['best_rank'] = $this->getBestRank($uid,$checkpoint,'checkpoint');//最佳排名
            }

        }

        if($type == 2 ) {  // 积分模式
            if(empty($endless_score)){
                $this->response('3','无尽分数不能为空');
            }
            $hash_key2 = self::PAOL_RANK_LIST2;//   Paol:rankList2
            $data = array('id'=>$userInfo['id'],'gold'=>$gold,'endless_score'=>$endless_score,'medal'=>$medal,'nickname'=>$userInfo['nickname'],'avatar'=>$userInfo['avatar']);
            //无尽排行榜
            $this->setRankList($hash_key2,2,$data,$userInfo['id'],'endless_score',$endless_score);//   更新缓存
            $data['endless_score'] = $endless_score;// 无尽成绩
            $data['best_endless_score'] = $this->getBestRank($uid,$checkpoint,'endless_score');//最佳排名
        }

        if($type == 3 ) {  // 积分模式
            if(empty($grade)) {
                $this->response('3','积分不能为空');
            }
            $data['grade'] = $grade;
            $dbname = self::DB_USER_NAME;
            $field = 'id,nickname,avatar,grade';
            // 最佳积分排名
            $data['best_grade'] = $this->commBestRank($uid,$dbname,$grade,$field,'grade','grade desc');
            M('users')->where($map)->save($data);
        }

        if(!empty($data)){
            $ret = M('users')->where($map)->save($data);
            if(empty($ret)){
                $this->response(1,'操作失败');
            }
        }

        $this->response(0,'操作成功');
    }


    // 最佳成绩排名
    public function getBestRank($uid,$checkType,$type) {

        $where['status'] = 2;  // 授权用户
        $where['good_score'] = array('neq',0,'AND');
        $where['nickname']  = array('not in',array('undefined',''));
        $where['avatar']  = array('not in', array('undefined',''));

        if($type == "checkpoint"){
            $ret = M('users')->field('id,nickname,avatar,score,checkpoint')->where($where)->order('checkpoint desc,id asc')->limit(200)->select();
        }else{
            $ret = M('users')->field('id,nickname,avatar,score,endless_score')->where($where)->order('endless_score desc,id asc')->limit(200)->select();
        }

        $rankNum = 0; // 排名
        if(!empty($ret)) {

            foreach($ret as $k=>$v) {

                if( $uid == $v['id'] && $checkType >= $v[$type] ) {
                    $rankNum = $k + 1;
                    break;
                }

                if( $checkType > $v[$type] ) {
                    $rankNum = $k + 1;
                    break;
                }
            }
        }

        if( $rankNum == 0 ) {

            $rankNum = count($ret) + 1 ;
        }

        return $rankNum;
    }


    // 每日大礼包（存储）
    public function setGiftData(){
        $uid = isset($this->uid)?$this->uid:I('post.id');  // 用户ID
        $json = I('post.data'); // Json

        if(empty($uid) || empty($json)){
            $this->response(1, "参数不能为空！");
        }else{
            $data['uid'] = $uid;
            $goods=htmlspecialchars_decode($json);
            $goods_list=html_entity_decode($goods);
            $data['data'] = $goods_list;//转义后
            $data['create_time'] = date('Y-m-d H:i:s');
            $user = M('git')->where(array('uid'=>$uid))->find();

            if($user){
                $res = M('git')->where(array('uid'=>$uid))->save($data);
            }else{
                $res = M('git')->add($data);
            }
            if($res){
                $this->response(0, "ok");
            }else{
                $this->response(2, "大礼包存储失败");
            }
        }
    }

    // 每日大礼包（获取）
    public function getGiftData(){
        $uid = isset($this->uid)?$this->uid:I('post.id');  // 用户ID

        if(empty($uid)){
            $this->response(1, "参数不能为空！");
        }else{
            $data['uid'] = $uid;
            $info = M('git')->field('uid,data')->where($data)->find();
            if(!empty($info)){
                $info['data'] = json_decode($info['data'],true);
            }
            $this->response(0, "ok",$info);
        }
    }

    // 获取session_key
    public function getSessionKey() {
        $gameType = self::GAME_TYPE;
        $code = I('code','','string');
        if(!$code) {
            $this->response(2,'code不能为空');
        }
        $info = $this->wxAuthor($gameType,$code);
        if(empty($info)) {
            $this->response(1,"操作失败");
        }

        $this->response(0, "ok",array('session_key'=>$info['session_key']));
    }


    // 解密数据
    public function cryptData()
    {
        $appid = C('APPID'); // Appid
        $userid = I('userid','','string'); // 用户userid
        $sessionKey = I('sessionKey','','string'); // sessionKey
        $encryptedData = I('encryptedData','','string'); // 加密数据
        $iv = I('iv','','string');
        $type = I('type',0,'int'); // 分享类型(1普通分享，2分享复活)

        if(empty($userid)){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }

        $pc = new \Org\Util\WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        $data = $data ? json_decode($data, true) : '';
        $openGId = isset($data['openGId']) ? $data['openGId'] : 0;

        if ($errCode == 0) {  // 解密成功

            $redis = REDIS('activity');
            $redis->select(2);
            $evening = date('Y-m-d 23:59:59'); //每日23点59分

            //$userKey = sprintf(self::QID_UID,$userid,$type);  //用户主键分享到群
            $userKey = sprintf(self::QID_UID,$userid,$type,$openGId);  //用户主键分享到群

            $shareKey = $redis->get($userKey);

            if( $type == 2 && $shareKey == 1  ) {
                $this->response(2,'每局同一群只能分享一次');
            }

            if( $type == 1 && $shareKey == 1  ) {
                $this->response(3,'每天同一群只能分享一次');
            }

            $redis->set($userKey,1);  // 标记
            $redis->exprieAt($userKey,strtotime(date('Y-m-d 23:59:59'))); // 每日23点59分过期

            // 群分享记录
            $groups = array(
                'userid' => $userid,
                'gid' => $openGId,
                'type'=> $type,
                'create_time'=>date('Y-m-d H:i:s')
            );
            $ret = M('share_group_log')->add($groups);

            $this->countLog('paol',self::PAOL_SHARE,1);  // 记录分享次数日志

            $jsons['errno'] = 0;
            $jsons['msg'] = '成功解密';
            $jsons['result'] = $data;
            $this->ajaxReturn($jsons);
        }else {
            $jsons['errno'] = $errCode;
            $jsons['msg'] = '解密失败';
            $this->ajaxReturn($jsons);
        }

        // $data['shareState'] = false;
        // // 群分享记录
        // $groups['userid'] = $userid;
        // $groups['gid'] = $openGId;
        // $groups['type'] = $type;
        // $groups['create_time'] = date('Y-m-d H:i:s');
        // if($ret = M('share_group_log')->add($groups)){
        //     $data['shareState'] = true;
        // }
    }

    // 获取服务器当前时间
    public function getServerTime(){
        $time = time();
        $this->response(0, "ok",$time);
    }


}